﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using mal.Web.Silverlight.MEF.Core.Interfaces;
using System.ComponentModel.Composition.Hosting;
using System.Collections.Generic;

namespace mal.Web.Silverlight.MEF.Core.Deployment
{
    public class DeploymentCatalogService : IDeploymentCatalogService
    {
        #region Member Fields

        private static DeploymentCatalogService m_Instance = null;
        private static readonly object s_InstanceLocker = new object();

        private static AggregateCatalog _aggregateCatalog;
        private Dictionary<string, DeploymentCatalog> _catalogs;

        private bool isInitialized = false;

        public bool IsInitialized
        {
            get { return isInitialized; }
            set { isInitialized = value; }
        }

        #endregion

        #region Public Contructor

        public DeploymentCatalogService()
        {
            _catalogs = new Dictionary<string, DeploymentCatalog>();
        }

        #endregion

        #region Singleton

        /// <summary>
        /// Singleton used to access to our object.
        /// </summary>
        public static DeploymentCatalogService Instance
        {
            get
            {
                lock (s_InstanceLocker)
                {
                    if (m_Instance == null)
                    {
                        m_Instance = new DeploymentCatalogService();
                    }

                    return m_Instance;
                }
            }
        }

        #endregion

        #region Public Methods

        public void Initialize()
        {
            _aggregateCatalog = new AggregateCatalog();
            _aggregateCatalog.Catalogs.Add(new DeploymentCatalog());

            _catalogs.Clear();
            _aggregateCatalog.Catalogs.Clear();

            CompositionHost.Initialize(_aggregateCatalog);
            IsInitialized = true;
        }

        public void AddXap(string uri)
        {
            DeploymentCatalog catalog;
            if (!_catalogs.TryGetValue(uri, out catalog))
            {
                catalog = new DeploymentCatalog(uri);
                catalog.DownloadAsync();
                _catalogs[uri] = catalog;
            }
            _aggregateCatalog.Catalogs.Add(catalog);
        }

        public void RemoveXap(string uri)
        {
            DeploymentCatalog catalog;
            if (_catalogs.TryGetValue(uri, out catalog))
            {
                _aggregateCatalog.Catalogs.Remove(catalog);
            }
        }

        #endregion
    }
}
